package com.ytrsoft.task;

import com.ytrsoft.bean.Message;
import com.ytrsoft.utils.ProcessManager;
import com.ytrsoft.ws.CmdSocket;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.LinkedBlockingQueue;

public class ProcessHandler extends ExecutorHandler implements ActionHandler {

    private final CmdSocket socket;
    private final LinkedBlockingQueue<byte[]> cmdQueue = new LinkedBlockingQueue<>();

    public ProcessHandler(CmdSocket socket) {
        this.socket = socket;
    }

    @Override
    public void doMessage(Message msg) {
        try {
            byte[] cmd = getCurCmd(msg);
            cmdQueue.put(cmd);
            start(msg);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private byte[] getCurCmd(Message msg) {
        String s = System.lineSeparator();
        String cmd = msg.getBody() + s;
        return cmd.getBytes();
    }

    @Override
    protected void running(Message msg) {
        ProcessManager manager = socket.getManager();
        Process process = manager.getProcess();
        OutputStream out = process.getOutputStream();
        try {
            byte[] cmd = cmdQueue.poll();
            if (cmd != null) {
                out.write(cmd);
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        socket.getManager().close();
        killNow();
    }

}
